<template>
  <div class="product-list-container">
    <!-- 顶部导航栏：搜索+分类 -->
    <div class="header-nav">
      <div class="category-selector">
        <el-select v-model="selectedCategory" placeholder="商品分类" class="category-select">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
        </el-select>
      </div>
      <div class="search-container">
        <el-input v-model="searchKeyword" placeholder="搜索商品" class="search-input" @keyup.enter="handleSearch">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
      </div>
    </div>

    <!-- 商品网格 -->
    <el-row :gutter="20" v-if="!showDetail">
      <el-col v-for="p in products" :key="p.id" :span="6">
        <div class="product-card">
          <el-card :body-style="{ padding: '0px' }">
            <img :src="p.imageUrl" class="product-image" @click="showProductDetail(p)" />
            <div class="product-info">
              <h3 class="product-name">{{ p.productName }}</h3>
              <p class="product-price">￥{{ p.price.toFixed(2) }}</p>
              <el-button type="primary" size="small" @click="showProductDetail(p)">选规格</el-button>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 商品详情页 -->
    <div class="product-detail-container" v-else>
      <img :src="selectedProduct.imageUrl" class="product-detail-image" />
      <h2>{{ selectedProduct.productName }}</h2>
      <p class="product-price">￥{{ selectedProduct.price.toFixed(2) }}</p>
      <p class="product-description">{{ selectedProduct.description || '暂无商品描述' }}</p>
      <!--      <p class="product-preparation-time">制作时间：{{ selectedProduct.preparationTime || '5' }} 分钟</p>-->

      <!-- 甜度 -->
      <div class="detail-option-group">
        <label class="option-label">甜度选择：</label>
        <el-radio-group v-model="selectedSweetness" class="radio-group" v-if="sweetnessOptions.length">
          <el-radio v-for="s in sweetnessOptions" :key="s.code" :label="s">{{ s.name }}</el-radio>
        </el-radio-group>
        <span v-else class="option-error">甜度数据加载失败，请刷新重试</span>
      </div>

      <!-- 冰量 -->
      <div class="detail-option-group">
        <label class="option-label">冰量选择：</label>
        <el-radio-group v-model="selectedIce" class="radio-group" v-if="iceOptions.length">
          <el-radio v-for="i in iceOptions" :key="i.code" :label="i">{{ i.name }}</el-radio>
        </el-radio-group>
        <span v-else class="option-error">冰度数据加载失败，请刷新重试</span>
      </div>

      <!-- 小料（只在有小料时显示） -->
      <div class="detail-option-group" v-if="ingredientList.length">
        <label class="option-label">小料选择（多选）：</label>
        <el-checkbox-group v-model="selectedIngredients" class="checkbox-group">
          <el-checkbox v-for="ing in ingredientList" :key="ing.id" :label="ing" class="ingredient-item">
            {{ ing.name }}（+￥{{ ing.extraPrice.toFixed(2) }}）
          </el-checkbox>
        </el-checkbox-group>
      </div>

      <!-- 数量 & 操作 -->
      <el-input-number v-model="selectedProduct.quantity" :min="1" :max="999" size="small" class="quantity-input" />
      <el-button type="primary" size="small" @click="addToHiddenCart(selectedProduct)">加入购物车</el-button>
      <el-button size="small" @click="hideProductDetail">返回</el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="!showDetail">
      <el-pagination background v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[12,24,36,48]"
                     layout="total,sizes,prev,pager,next,jumper" :total="total" @size-change="handleSizeChange"
                     @current-change="handlePageChange" />
    </div>

    <!-- 悬浮购物车 -->
    <div class="cart-float-btn">
      <el-badge :value="hiddenCart.length" :hidden="!hiddenCart.length">
        <el-button circle type="primary" :icon="ShoppingCart" @click="cartDrawer=true" />
      </el-badge>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer v-model="cartDrawer" title="购物车" direction="rtl" size="320px">
      <div v-if="!hiddenCart.length" class="empty-cart">购物车是空的</div>
      <div v-else>
        <div v-for="(item,idx) in hiddenCart" :key="idx" class="cart-item">
          <img :src="item.product.imageUrl" class="cart-item-image" />
          <div class="cart-item-info">
            <h3>{{ item.product.productName }}</h3>
            <p>单价：￥{{ item.product.price.toFixed(2) }}</p>
            <p>规格：{{ item.sweetness.name }} · {{ item.ice.name }}</p>
            <p v-if="item.ingredients.length">
              小料：{{ item.ingredients.map(i=>i.name).join('、') }}
              <span class="ing-price">（+￥{{ item.ingredients.reduce((s,v)=>s+v.extraPrice,0).toFixed(2) }}）</span>
            </p>
            <p>数量：{{ item.quantity }} | 小计：￥{{ item.itemTotal.toFixed(2) }}</p>
            <el-button type="danger" size="small" @click="removeFromHiddenCart(idx)">移除</el-button>
          </div>
        </div>
        <div class="cart-footer">
          <div class="total-amount">订单总金额：<span>￥{{ totalOrderAmount.toFixed(2) }}</span></div>
          <el-select v-model="selectedPaymentMethod" placeholder="选择支付方式" class="payment-select">
            <el-option label="现金支付" value="现金支付" />
            <el-option label="扫码支付" value="扫码支付" />
            <el-option label="会员支付" value="会员支付" />
          </el-select>
          <el-button type="danger" @click="clearCart">一键清空</el-button>
          <el-button type="primary" @click="createOrder">生成订单</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 会员选择弹窗 -->
    <el-dialog title="会员支付" v-model="isMemberPayDialogOpen" width="400px">
      <el-form :model="memberPayForm" :rules="memberPayRules" ref="memberPayFormRef" label-width="100px">
        <el-form-item label="会员手机号" prop="phone">
          <el-input v-model="memberPayForm.phone" placeholder="请输入会员手机号" maxlength="11"
                    @input="handleMemberPhoneInput" clearable />
        </el-form-item>
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="memberPayForm.name" placeholder="自动匹配" disabled />
        </el-form-item>
        <el-form-item label="消费金额" prop="amount">
          <el-input v-model="memberPayForm.amount" placeholder="订单总金额" disabled />
        </el-form-item>
        <el-form-item label="积分到账" class="text-success">
          本次消费将获得 {{ memberPayForm.amount ? Number(memberPayForm.amount).toFixed(0) : 0 }} 积分（1元=1积分）
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isMemberPayDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="confirmMemberPay">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import http from '@/axios/http'
import { Search, ShoppingCart } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'

/* -------- 商品列表 -------- */
const products = ref([])
const pageNum = ref(1)
const pageSize = ref(12)
const total = ref(0)
const selectedCategory = ref('')
const categories = ref([])
const searchKeyword = ref('')

/* -------- 详情/选项 -------- */
const showDetail = ref(false)
const selectedProduct = ref({})
const sweetnessOptions = ref([])
const iceOptions = ref([])
const ingredientList = ref([])
const selectedSweetness = ref({})
const selectedIce = ref({})
const selectedIngredients = ref([])

/* -------- 购物车 -------- */
const cartDrawer = ref(false)
const hiddenCart = ref([])
const selectedPaymentMethod = ref('')
const totalOrderAmount = computed(() => hiddenCart.value.reduce((s, i) => s + i.itemTotal, 0))

/* -------- 会员支付相关 -------- */
const isMemberPayDialogOpen = ref(false)
const memberPayFormRef = ref(null)
const memberPayForm = ref({
  phone: '',
  name: '',
  amount: '',
  memberId: ''
})
const memberPayRules = ref({
  phone: [
    { required: true, message: '请输入会员手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '未匹配到会员信息', trigger: 'blur' }
  ]
})

/* -------- 数据获取（核心修复） -------- */
const fetchCategories = async () => {
  const res = await http.get('/glsb/getAllCategories')
  if (res.data.result === 'success') categories.value = res.data.data || []
}

// 修复：甜度请求 + 数据校验
const fetchSweetness = async () => {
  const res = await http.get('/glsb/getAllSweetness')
  if (res.data.result === 'success') {
    sweetnessOptions.value = res.data.data.map(i => ({ code: i.sweetnessCode, name: i.sweetnessName }))
    selectedSweetness.value = sweetnessOptions.value[2] || sweetnessOptions.value[0]
  }
}

// 修复：冰度请求 + 数据校验
const fetchIceLevel = async () => {
  const res = await http.get('/glsb/getAllIceLevel')
  if (res.data.result === 'success') {
    iceOptions.value = res.data.data.map(i => ({ code: i.iceCode, name: i.iceName }))
    selectedIce.value = iceOptions.value[1] || iceOptions.value[0]
  }
}

// 新增：串行加载冰度和甜度（避免并发冲突）
const fetchSweetnessAndIce = async () => {
  await fetchSweetness()
  await fetchIceLevel()
}

const fetchProducts = async () => {
  const params = { pageNum: pageNum.value, pageSize: pageSize.value }
  const url = searchKeyword.value ? '/glsb/get_product_by' : '/glsb/get_all_products'
  const body = searchKeyword.value ? { ...params, productName: searchKeyword.value } : { ...params, productCategory: selectedCategory.value }
  const res = await http.post(url, body)
  if (res.data.result === 'success') {
    products.value = (res.data.data.list || []).map(p => ({
      ...p,
      quantity: 1,
      imageUrl: (!p.imageUrl || p.imageUrl === '/') ? 'https://via.placeholder.com/200x200?text= 暂无图片' : p.imageUrl
    }))
    total.value = res.data.data.total || 0
  }
}

const fetchIngredients = async (productId) => {
  const res = await http.post('/glsb/getIngredientsByProductId', { productId })
  if (res.data.result === 'success' && res.data.data.length) {
    ingredientList.value = res.data.data.map(i => ({
      id: i.id,
      name: i.ingredient_name,
      extraPrice: Number(i.extra_price)
    }))
    ingredientList.value.unshift({ id: -1, name: '不添加小料', extraPrice: 0 })
  } else {
    ingredientList.value = []
  }
}

/* -------- 详情/购物车（修复：重置数据） -------- */
const showProductDetail = async (p) => {
  // 关键：重置所有选项数据，避免残留
  sweetnessOptions.value = []
  iceOptions.value = []
  selectedSweetness.value = {}
  selectedIce.value = {}
  selectedIngredients.value = []

  selectedProduct.value = { ...p, quantity: 1 }
  showDetail.value = true

  // 串行加载冰度甜度 + 小料（避免冲突）
  await fetchSweetnessAndIce()
  fetchIngredients(p.id)
}

const hideProductDetail = () => {
  showDetail.value = false
}

/* 真正加入购物车逻辑 */
const doAdd = (product) => {
  const key = `${product.id}-${selectedSweetness.value.code}-${selectedIce.value.code}`
  const idx = hiddenCart.value.findIndex(
      i => `${i.product.id}-${i.sweetness.code}-${i.ice.code}` === key
  )
  const base = product.price
  const extra = selectedIngredients.value.reduce((s, ig) => s + ig.extraPrice, 0)
  const itemTotal = (base + extra) * product.quantity

  if (idx > -1) {
    hiddenCart.value[idx].quantity += product.quantity
    hiddenCart.value[idx].itemTotal += itemTotal
  } else {
    hiddenCart.value.push({
      product: { ...product },
      quantity: product.quantity,
      sweetness: { ...selectedSweetness.value },
      ice: { ...selectedIce.value },
      ingredients: [...selectedIngredients.value],
      itemTotal
    })
  }

  hideProductDetail()
  ElMessage.success('商品已加入购物车')
}

/* 无小料弹框 */
const addToHiddenCart = (product) => {
  if (ingredientList.value.length && !selectedIngredients.value.length) {
    ElMessageBox.confirm(
        '您还没有选择小料，是否继续？',
        '小料提醒',
        { confirmButtonText: '不添加小料', cancelButtonText: '去选小料', type: 'warning' }
    ).then(() => doAdd(product)).catch(() => {})
  } else {
    doAdd(product)
  }
}

const removeFromHiddenCart = (idx) => {
  hiddenCart.value.splice(idx, 1)
  ElMessage.info('商品已从购物车移除')
}

const clearCart = async () => {
  await ElMessageBox.confirm('确定清空购物车？', '提示', { type: 'warning' })
  hiddenCart.value = []
  ElMessage.success('购物车已清空')
}

/* -------- 会员支付相关方法 -------- */
const handleMemberPhoneInput = async (val) => {
  if (val.length === 11) {
    try {
      const res = await http.post('/glsb/get_member_by_phone', { phone: val })
      if (res.data.result === 'success' && res.data.data) {
        memberPayForm.value.name = res.data.data.name
        memberPayForm.value.memberId = res.data.data.id
      } else {
        memberPayForm.value.name = ''
        memberPayForm.value.memberId = ''
        ElMessage.warning('未查询到该会员信息')
      }
    } catch (e) {
      ElMessage.error('会员信息查询失败')
      console.error(e)
    }
  }
}

const confirmMemberPay = async () => {
  try {
    await memberPayFormRef.value.validate()
    await submitOrderWithMember()
    isMemberPayDialogOpen.value = false
    hiddenCart.value = []
    selectedPaymentMethod.value = ''
    cartDrawer.value = false
  } catch (e) {
    ElMessage.error('支付失败，请重试')
    console.error(e)
  }
}

/* 提交订单 */
const createOrder = async () => {
  if (!hiddenCart.value.length) return ElMessage.warning('购物车为空')
  if (!selectedPaymentMethod.value) return ElMessage.warning('请选择支付方式')

  if (selectedPaymentMethod.value === '会员支付') {
    memberPayForm.value = {
      phone: '',
      name: '',
      amount: totalOrderAmount.value.toFixed(2),
      memberId: ''
    }
    isMemberPayDialogOpen.value = true
    return
  }

  const orderProducts = hiddenCart.value.map(item => ({
    productId: item.product.id,
    productName: item.product.productName,
    quantity: item.quantity,
    price: item.product.price,
    sweetnessName: item.sweetness.name,
    iceName: item.ice.name,
    selectedIngredients: item.ingredients.map(ing => ({
      ingredientId: ing.id,
      ingredientName: ing.name,
      extraPrice: ing.extraPrice
    }))
  }))

  const orderData = {
    userId: 1, // 替换为真实用户ID
    paymentMethod: selectedPaymentMethod.value,
    orderProducts,
    totalAmount: totalOrderAmount.value
  }

  try {
    const res = await http.post('/glsb/createOrder', orderData)
    if (res.data.result === 'success') {
      ElMessage.success('订单生成成功！')
      hiddenCart.value = []
      selectedPaymentMethod.value = ''
      cartDrawer.value = false
    } else {
      ElMessage.error(`订单生成失败：${res.data.error || '未知错误'}`)
    }
  } catch (e) {
    ElMessage.error('网络异常，订单提交失败')
  }
}

const submitOrderWithMember = async () => {
  const orderProducts = hiddenCart.value.map(item => ({
    productId: item.product.id,
    productName: item.product.productName,
    quantity: item.quantity,
    price: item.product.price,
    sweetnessName: item.sweetness.name,
    iceName: item.ice.name,
    selectedIngredients: item.ingredients.map(ing => ({
      ingredientId: ing.id,
      ingredientName: ing.name,
      extraPrice: ing.extraPrice
    }))
  }))

  const orderData = {
    userId: 1, // 替换为真实用户ID
    paymentMethod: '会员支付',
    orderProducts,
    totalAmount: totalOrderAmount.value,
    memberId: memberPayForm.value.memberId,
    memberPhone: memberPayForm.value.phone
  }

  try {
    const res = await http.post('/glsb/createOrderWithMember', orderData)
    if (res.data.result === 'success') {
      ElMessage.success(`订单生成成功！会员已获得 ${totalOrderAmount.value.toFixed(0)} 积分`)
    } else {
      ElMessage.error(`订单生成失败：${res.data.error || '未知错误'}`)
    }
  } catch (e) {
    ElMessage.error('网络异常，订单提交失败')
  }
}

/* 分页/搜索 */
const handleSizeChange = (s) => {
  pageSize.value = s;
  fetchProducts()
}

const handlePageChange = (p) => {
  pageNum.value = p;
  fetchProducts()
}

const handleSearch = () => {
  pageNum.value = 1;
  fetchProducts()
}

/* 监听分类变化 */
watch(selectedCategory, () => {
  pageNum.value = 1;
  fetchProducts()
})

/* 初始化 */
onMounted(async () => {
  fetchCategories()
  await fetchSweetnessAndIce() // 串行加载初始化数据
  fetchProducts()
})
</script>

<style scoped>
.product-list-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  font-family: Arial, sans-serif;
}

.header-nav {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 8px;
  width: 400px;
}

.search-input {
  flex: 1;
}

.category-select {
  width: 220px;
}

.product-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.3s;
}

.product-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.03);
}

.product-info {
  padding: 12px;
  background: #fff;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  font-size: 16px;
  margin: 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 14px;
  color: #ff4444;
  margin: 0;
}

.product-detail-container {
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.product-detail-image {
  width: 400px;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
}

.detail-option-group {
  width: 100%;
  max-width: 600px;
  margin: 8px 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 8px 0;
}

.ingredient-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.quantity-input {
  margin: 8px 0;
}

.add-cart-btn,
.back-btn {
  margin: 0 8px;
}

.ing-price {
  color: #999;
  margin-left: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.cart-float-btn {
  position: fixed;
  right: 30px;
  bottom: 60px;
  z-index: 1000;
}

.empty-cart {
  text-align: center;
  color: #999;
  padding: 60px 20px;
  font-size: 14px;
}

.cart-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  gap: 12px;
}

.cart-item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.cart-item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.cart-item-name {
  font-size: 14px;
  margin: 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cart-item-price,
.cart-item-option,
.cart-item-ingredient,
.cart-item-quantity {
  font-size: 12px;
  margin: 0;
  color: #666;
}

.cart-footer {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #eee;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.total-amount {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  text-align: right;
}

.total-amount span {
  color: #ff4444;
  font-size: 16px;
}

.payment-select {
  width: 100%;
}

/* 新增错误样式 */
.option-error {
  color: #f56c6c;
  font-size: 12px;
  padding: 8px 0;
}

/* 会员支付弹窗样式 */
.el-dialog__body .el-form {
  margin-top: 10px;
}

.el-form-item__label {
  font-weight: 500;
}

.text-success {
  color: #67c23a;
  font-size: 13px;
  margin-top: 5px;
}
</style>
